import faceUtil from "@/util/emojiMap.js";
//弹窗提示
function utilAlert(msg, iconType) {
    uni.showToast({
        title: msg == null ? "" : msg,
        icon:iconType==null?"none":iconType,
        duration: 1500
    });
    return;
};
//加载中提示
function utilLoading(tip,mask){
    uni.showLoading({
        title: tip?tip:'加载中',
        mask:mask?mask:false
    });
    setTimeout(function (){
         uni.hideLoading();
    },10000)
};
//清理缓存
function clearVuex(that){
	console.log("清除缓存");
	that.$u.vuex('vuex_userInfo',{});
	that.$u.vuex('vuex_token','');
	that.$u.vuex('vuex_loginParam.password','');
	that.$u.vuex('vuex_loginParam.userDeviceId','');
	that.$u.vuex('circleData',[]);
	that.$u.vuex('vuex_friendCircleUnreadCount',0);
	that.$u.vuex('vuex_groupList', []);
}
//信息提示音
function palyMsgTips(that){
	let innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = false;
	innerAudioContext.volume=1;
	innerAudioContext.src = "/static/mp3/msgTip2.mp3";
	innerAudioContext.startTime = 0;
	innerAudioContext.onPlay(() => {
		uni.vibrateLong({})
	});
	innerAudioContext.onError((res) => {
		//console.log("===提示音播放异常====",res);
		if(that.vuex_OSPlat=="ios"){
			uni.vibrateLong({})
		};
		innerAudioContext.destroy()
	});
	innerAudioContext.onEnded(function(){
		innerAudioContext.destroy();
	})
	innerAudioContext.onStop(function(){
		innerAudioContext.destroy();
	})
	innerAudioContext.play();
}

function palyMsgTipSelected(self, chatGroupId) {
	let currentUserId = self.vuex_userInfo.id;
	let param = {
		chatGroupId: chatGroupId,
		userId: currentUserId
	};
	self.$u.api.chatGroup.getChatPingBiFlag(param).then(res => {
		//console.log("获取是否屏蔽消息标志的结果",res);
		if (res.code == 200 && res.data == true) {
			//没有屏蔽,提示音提示
			palyMsgTips(self);
		} else {
			return;
		}
	}).catch(res => {
		console.log("获取是否屏蔽消息标志的结果异常");
	});
}

//字节转换为可视化单位
function byteConvert(bytes) {
      //console.log("字节量"+bytes);
      if (isNaN(bytes)) {
        return '';
      }
      var symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var exp = Math.floor(Math.log(bytes)/Math.log(2));
      if (exp < 1) {
        exp = 0;
      }
      var i = Math.floor(exp / 10);
      bytes = bytes / Math.pow(2, 10 * i);
      if (bytes.toString().length > bytes.toFixed(2).toString().length) {
        bytes = bytes.toFixed(2);
      }
      return bytes + ' ' + symbols[i];
}

//全局上传文件
function globalUpload(that,callback){
	if (typeof callback.success != 'function') {
	  callback.success = () => {};
	}
	if (typeof callback.fail != 'function') {
	  callback.fail = () => {};
	}
	if (typeof callback.complete != 'function') {
	  callback.complete = () => {};
	}
	let obj= callback.param;
	if(obj==null||obj==undefined){
		console.log("上传文件的参数丢失!!!")
		return ;
	}
	let target = that.$u.api.multipartAddress.target;
	let uploadFileUrl=that.$u.api.multipartAddress.updload;
	let saveDir="chattingFiles";
	if(obj.savePath){
		saveDir =obj.savePath;
	}
	let uploadUrl =uploadFileUrl+"&dir="+saveDir;
	let filePath = obj.filePath;
	let isSuccess = false;
	//console.log("上传文件的uploadUrl",uploadUrl);
	//console.log("上传文件的filePath",filePath);
	if (uploadUrl && filePath) {
		const uploadTask = uni.uploadFile({
			url: uploadUrl,
			filePath: filePath,
			name: 'fileName',
			header: {
				'Access-Control-Allow-Origin': '*',
				'TOKEN_IM': that.vuex_token,
			},
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					let resObj = JSON.parse(uploadFileRes.data);
					console.log("上传文件的响应结果",resObj);
					if (resObj.code == 200) {
						let fileInfo= resObj.data;
						if(fileInfo.fullPath&&target=="local"){
							let _url = that.$u.api.multipartAddress.getFileByPath + fileInfo.fullPath;
							fileInfo.url = _url;
						}else{
							fileInfo.url=fileInfo.fullPath;
						}
						if(fileInfo.fileSize){
							fileInfo.fileSize= byteConvert(fileInfo.fileSize); 
						}
						fileInfo.fileSaveTarget =target;
						 isSuccess = true;
						 callback.success({
							 'result':fileInfo,
							 'code':1,
						 });
					} else {
						isSuccess = false;
						callback.fail({
							 'result':null,
							 'code':0,
						});
					}
				}else {
					isSuccess = false;
					callback.fail({
						 'result':null,
						 'code':0,
					});
				}
			},
			fail: function() {
				callback.fail({
					 'result':null,
					 'code':-1,
				});
			}
		});
	}
}
//安卓插件获取视频第一帧图片
function androidCreateVideoThumbnail(that,tempFilePath,callback){
	if(!that){
		console.log("传that!!!!!");
		callback.complete("");
	}
	if(!tempFilePath){
		callback.complete("");
	}
	console.log("=====tempFilePath====",tempFilePath);
	const plugin = uni.requireNativePlugin('K-VideoInfoModule');
	if(plugin){
		plugin.getVideoFrame({oriPath:tempFilePath}, result => {
			if(result.code==0){
				let thumbnailPath= result.framePicPath;
				let localSrc=`file://${thumbnailPath}`;
				return getVideoThumbnail(that,localSrc,callback);
			}else{
				callback.complete("");
			}
		});
	}else{
		callback.complete("");
	}
	
}
//ios插件获取视频第一帧图片
function iosCreateVideoThumbnail(that,tempFilePath,callback) {
	if(!that){
		callback.complete("");
	}
	if(!tempFilePath){
		callback.complete("");
	}
    let videoThumbnail = uni.requireNativePlugin("YS-VideoThumbnail");
	if(videoThumbnail){
		console.log("是否有file://打头",tempFilePath);
		//需要去除file:// 不然获取不到视频
		if (tempFilePath.indexOf("file://")===0) {
		    tempFilePath = tempFilePath.slice(7);
		}
		// 图片存放路径，目前原生代码写死使用png格式生成
		let thumbnailPath = tempFilePath.slice(0, tempFilePath.lastIndexOf(".")) + ".png";
		let result = videoThumbnail.saveVideoThumbnail({
		    "videoUrl": tempFilePath, // 视频路径
		    "thumbPath": thumbnailPath // 图片保存路径
		});
		console.log("iOS获取视频第一帧结果",result);
		if(result==='success'){
			let src=`file://${thumbnailPath}`;
			getVideoThumbnail(that,src,callback);
		}else{
			callback.complete("");
		}
	}
    else{
		callback.complete("");
	}
}

//将通过插件获取到视频第一帧图片上传到服务器，并返回结果
function getVideoThumbnail(that,fileTempPath,callback){
	uni.uploadFile({
		url:that.$u.api.multipartAddress.updload,
		filePath: fileTempPath,
		name: 'fileName',
		header: {
			'Access-Control-Allow-Origin': '*',
			'TOKEN_IM': that.vuex_token,
		},
		success: (uploadFileRes) => {
			if (uploadFileRes.statusCode == 200 && uploadFileRes.data.length > 0) {
				let resObj = JSON.parse(uploadFileRes.data);
				console.log("上传视频第一帧图片返回结果",resObj);
				if (resObj.code == 200) {
					let fileInfo= resObj.data;
					callback.complete(fileInfo.fullPath);
				} else {
					callback.complete("");
				}
			}else {
				callback.complete("");
			}
		},
		fail: function() {
			callback.complete("");
		},
		complete:function(){
			callback.complete("");
		}
	});
}
//二维码业务类型
const scan_business_code={
	invited_join_group:{code:1,expireTime:2}, //邀请入群 
	personal_info:{code:2,expireTime:-1},	 //个人信息
	groupInfo:{code:3,expireTime:-1},		//群信息
}
//扫码二维码
//扫描二维码
function scanQRcode(that,callback){
	if (typeof callback.complete != 'function') {
		callback.complete = () => {};
	}
	const hwscan = uni.requireNativePlugin('YT-hwScan'); //插件
	var scanOption = {
		scanMode: "defaultMode", //扫描模式
		scanType: [],
		scanResultImage: false, //是否返回扫描图片
		pictureBase64: "", //要识别的图片（转base64）
		scanTypeOptions: {
			scanTitle: "友圈儿", //导航栏标题
			showPhotoAlbum: true, //显示扫描相册
			showLight: false, //显示手电筒  
			showScanFrame: true, //是否显示扫描框
			showLine: true, //是否显示扫描线条
			scanLineColor: "#FF00FF", //扫描线条背景色
			lineAnimationDuration: 3, //扫码线条动画时间 默认 3秒
			sleep: 3, //连续扫描时间间隔，默认1秒
			showScanMessage: true, //显示扫描框上方提示文字
			scanMessage: "将码放入取景框,即可自动扫描", //扫描框上方提示文字
			scanFrameSize: 300, //扫描框大小
			scanFrameBackgroudColor: "#1f00BCD4", //扫描框背景
			scanFrameStrokeColor: "#e1ffff", //扫描框外边框
			scanContinue: false, //连续扫描
			scanFrameRoundedCorner: 6 //扫描框圆角
		},
		multiOptions: { //多码配置
			oneCodeReturn: true, //只扫描到一个码直接返回
			multicodeReturn: false, //true：返回多码,为false选择多选1
			scanCancelBtnTitle: "取消", //多码结果也左上角按钮文字
			scanResultTips: "已扫描到码请选择", //扫描结果页选择码提示文字
			identificationNumber: 3, //识别到指定码数量
			identificationNumberReturn: true, //识别到指定数量码才返回
			identificationMoreMax: false //识别的码多余指定识别的码返回
		}
	}
	hwscan.hwScan({
		scanOptions: scanOption
	}, (res) => {
		// 1.0.9新增  结构化数据：从使用特定内容格式编码的二维码、条码中提取的有效信息。
		//Scan Kit当前已支持结构化提取Wi-Fi、EMAIL、PHONE、ISBN、PRODUCT、SMS、TEXT、URL、
		//CONTACT INFO、GEO、CALENDAR EVENT、DRIVER LICENSE这12种码中的有效信息并返回给您，
		//以便于您快速构建对应的服务。
		//（iOS与Android返回的字段不同请参照华为扫描官方SDK文档，或通过JSON.stringify(res.codeTypeData)打印查看）
		console.log("扫码信息",res);
		if (uni.getSystemInfoSync().platform == "ios") {
			let codeContent= res.codeTypeData;
			let scanType= codeContent.scanType;
			if(scanType=='WebSite'){
				plus.runtime.openURL(codeContent.url);
				callback.complete(null)
				return;
			}
		}
		let qrModelInfo = JSON.parse(decodeURIComponent(res.result));
		console.log("扫描结果",qrModelInfo);
		let plat = qrModelInfo.plat;
		if (plat != null || plat != undefined && plat == 'cyd') {
			let createTimeStamp = qrModelInfo.createTimeStamp;
			let qrExpireTime = qrModelInfo.expireTime;
			let nowTimestamp = new Date().getTime();
			let during = Number(nowTimestamp) - Number(createTimeStamp);
			let duringHours = during / 1000 / 3600;
			if (qrExpireTime != -1 && duringHours > qrExpireTime) {
				utilAlert("二维码已过期");
				callback.complete(null);
			} else {
				delete qrModelInfo.plat;
				callback.complete(qrModelInfo);
			}
		} else {
			console.log("非本平台二维码");
			utilAlert("非本平台二维码!");
			callback.complete(ret);
		}
	})
}
//聊天内容信息转换
function transform(content, fileSize, fileSuffix,linkName) {
	if (fileSize === undefined) {
		fileSize = '';
	}
	if (fileSuffix === undefined) {
		fileSuffix = '';
	}
	let html = function(end) {
		return new RegExp('\\n*\\[' + (end || '') +
			'(code|pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)]\\n*',
			'g');
	};
	if (content)
	{
		content = content.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/'/g, '&#39;')
			.replace(/"/g, '&quot;') // XSS
			.replace(html(), '<$1 $2>')
			.replace(html('/'), '</$1>') // 转移HTML代码
			.replace(/\n/g, '<br>'); // 转义换行
		content=getUrl(content);	
		content=content.replace(/face\[([^\s\[\]]+?)]/g, function(face) {
				let alt = face.replace(/^face/g, '');
				let fa =faceUtil.emojiMap;
				let srcPrefix=faceUtil.emojiUrl;
				let imageSrc=srcPrefix+ fa[alt];
				//console.log("表情",imageSrc);
				let imgContent= '<img class="emoji" src="' +imageSrc+ '"/>';
				return imgContent;
			})
			// 转义图片
			.replace(/img\[([^\s]+?)]/g, function(img) {
				let href = img.replace(/(^img\[)|(]$)/g, '');
				return '<img class="message-img" src="' + href + '" alt="消息图片不能加载">';
			})
			// 转义文件
			.replace(/file\([\s\S]+?\)\[[\s\S]*?]/g, function(str) {
				let href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
				let text = (str.match(/\)\[([\s\S]*?)]/) || [])[1];
				if (!href) return str;
				return '<div class="flex"><i class="iconfont icon-xiazai-yun"></i><a class="message-file"  href="' +
					href + '">' + (text || href) + '</a><span>' + fileSize + '</span></div>'
			})
			// 转义音频
			.replace(/audio\[([^\s]+?)]/g, function(audio) {
				return '<div class="message-audio" data-src="' + audio.replace(/(^audio\[)|(]$)/g, '') +
					'"><i class="layui-icon">&#xe652;</i><p>音频消息</p></div>';
			})
			// 转义视频
			.replace(/video\[([^\s]+?)]/g, function(video) {
				return '<div class="message-video"  data-src="' + video.replace(/(^video\[)|(]$)/g, '') +
					'"><i class="layui-icon">&#xe652;</i></div>';
			})
			// 转义链接
			.replace(/a\([\s\S]+?\)\[[\s\S]*?]/g, function(str) {
				let href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
				let text = (str.match(/\)\[([\s\S]*?)]/) || [])[1];
				if (!href) return str;
				if(linkName&&linkName.length>0){
					return '<a href="' + href + '" target="_blank">' + linkName + '</a>';
				};
				return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
			})
				
	}
	return content;
}

function getUrl (str) {
	let oldStr=str;
    const reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
    str = str.match(reg);
    if (str && str.length > 0) {
		let a="<a href='"+str+"'>"+str+"</a>";
		let newContent= oldStr.replace(new RegExp(reg, 'g'),a);
		return newContent;
    }else{
		return oldStr;
	}
}


// 获取CID
function getCid(callback) {
	// 如果已经获取过CID，则直接返回
	if (getCid.cid) {
		//console.log("已经获取过CID，则直接返回",getCid.cid); 
		callback(getCid.cid);
		return;
	}
	// 获取客户端推送信息
	// #ifdef APP-PLUS
	var clientInfo = plus.push.getClientInfo();
	if (clientInfo) {
		console.log("========clientInfo====",clientInfo);
		// 获取CID
		var cid = clientInfo.clientid;
		// 缓存CID
		getCid.cid = cid;
	} else {
		var cid = new Date().getTime();
		getCid.cid = cid;
	}
	// #endif
	// #ifndef APP-PLUS
	var cid = new Date().getTime();
	getCid.cid = cid;
	// #endif
	// 调用回调函数
	callback(cid);
}

//复制
function uniCopy({content,success,error}) {
	if(!content) return error('复制的内容不能为空 !')
	content = typeof content === 'string' ? content : content.toString() // 复制内容，必须字符串，数字需要转换为字符串
	/**
	 * 小程序端 和 app端的复制逻辑
	 */
	//#ifndef H5
	uni.setClipboardData({
		data: content,
		showToast:false,
		success: function() {
			success("复制成功~")
			console.log('success');
		},
		fail:function(){
			success("复制失败~")
		}
	});
	//#endif

	/**
	 * H5端的复制逻辑
	 */
	// #ifdef H5
	if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
		// 不支持
		error('浏览器不支持')
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	if(result){
		success("复制成功~")
	}else{
		error("复制失败，请检查h5中调用该方法的方式，是不是用户点击的方式调用的，如果不是请改为用户点击的方式触发该方法，因为h5中安全性，不能js直接调用！")
	}
	textarea.remove()
	// #endif
}
//格式化聊天信息显示
function fromatMsgTime(stringTime) {
	//stringTime="2024-05-19 20:21:49";
	let hm= stringTime.substring(10,16);
	let msgdate=parseTime(stringTime);
	let timestamp =msgdate.getTime();
	let currentData=new Date();
	const currentTime =currentData.getTime();
	const timeDifference = currentTime - timestamp;
	if (timeDifference < 60000) { // 少于1分钟
		return '刚刚';
	} else if (timeDifference < 3600000) { // 少于1小时
		const minutes = Math.floor(timeDifference / 60000);
		return hm;
	}
	else if (timeDifference < 86400000) { //少于24小时
			const date = new Date();
			const year = date.getFullYear();
			const month = date.getMonth() + 1;
			const day = date.getDate();
			const today = `${year}/${month}/${day}`; 
		    const todayTime = new Date(today).getTime(); // 当天凌晨的时间
			if(todayTime>timestamp){
				return "昨天 "+hm;
			}else{
				return "今天 "+hm;
			}	
	}else if (timeDifference < 604800000) { // 少于1周
		let weekDayNum= getDayOfWeek(stringTime);
		//console.log("weekDayNum",weekDayNum);
		let pre="";
		const arrweeks =['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
		if(weekDayNum>7){
			weekDayNum=weekDayNum-7;
			pre="上周 "
		};
		return pre+arrweeks[weekDayNum]+" "+hm;
	}else{
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = ('0' + (date.getMonth() + 1)).slice(-2);
		const day = ('0' + date.getDate()).slice(-2);
		return `${year}-${month}-${day} `+hm;
	} 
}
//将日期转为星期几，大于7是上周，比如10,10-7=3上周星期三  0是星期天
function getDayOfWeek(date) {
  const currentDate = new Date();
  const currentDayOfWeek = currentDate.getDay(); // 0-6, 0 是周日
  const currentDateAtStartOfWeek = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() - currentDayOfWeek);
 
  const dateToCheck = new Date(date);
  const dateToCheckAtStartOfWeek = new Date(dateToCheck.getFullYear(), dateToCheck.getMonth(), dateToCheck.getDate() - dateToCheck.getDay());
 
  if (dateToCheckAtStartOfWeek.getTime() >= currentDateAtStartOfWeek.getTime()) {
    // 本周
    return dateToCheck.getDay();
  } else {
    // 上周
    return dateToCheck.getDay() + 7;
  }
}


//日期格式的字符串转换为时间
function parseTime(timeStr){
	let t= timeStr.replace(/-/g,"/");
	let date=new Date(t);
	//console.log("日期格式的字符串转换为时间",date);
	return date;
	//return date.getTime();
}
//时间戳转化为日期字符串
function getTimeStr(timestamp,type){
	var _data = timestamp;
	//如果是13位正常，如果是10位则需要转化为毫秒
	if (String(timestamp).length == 13) {
	  _data = timestamp
	} else {
	  _data = timestamp*1000
	}
	const time = new Date(_data);    
	const Y = time.getFullYear();
	const Mon = time.getMonth() + 1< 10 ? '0'+(time.getMonth()+1) : time.getMonth()+1;
	const Day = time.getDate()< 10 ? '0'+time.getDate():time.getDate();
	const H = time.getHours()< 10 ? '0'+time.getHours():time.getHours();
	const Min = time.getMinutes()< 10 ? '0'+time.getMinutes():time.getMinutes();
	const S = time.getSeconds()< 10 ? '0'+time.getSeconds():time.getSeconds();
	//自定义选择想要返回的类型
	if(type=="Y"){
	  return `${Y}-${Mon}-${Day}`
	}else if(type=="H"){
	  return `${H}:${Min}:${S}`
	}
	else if(type=="M"){
	  return `${H}:${Min}`
	}
	else{
	  return `${Y}-${Mon}-${Day} ${H}:${Min}:${S}`
	}
}
//秒数转化为时分秒
function formatSeconds(value) {
	//  秒
	let second = parseInt(value);
	//  分
	let minute = 0;
	//  小时
	let hour = 0;
	//  天
	//  let day = 0
	//  如果秒数大于60，将秒数转换成整数
	if (second > 60) {
		//  获取分钟，除以60取整数，得到整数分钟
		minute = parseInt(second / 60);
		//  获取秒数，秒数取佘，得到整数秒数
		second = parseInt(second % 60);
		//  如果分钟大于60，将分钟转换成小时
		if (minute > 60) {
			//  获取小时，获取分钟除以60，得到整数小时
			hour = parseInt(minute / 60);
			//  获取小时后取佘的分，获取分钟除以60取佘的分
			minute = parseInt(minute % 60);
			//  如果小时大于24，将小时转换成天
			//  if (hour > 23) {
			//    //  获取天数，获取小时除以24，得到整天数
			//    day = parseInt(hour / 24)
			//    //  获取天数后取余的小时，获取小时除以24取余的小时
			//    hour = parseInt(hour % 24)
			//  }
		}
	}
	let result = '' + (parseInt(second)<10?'0'+parseInt(second):parseInt(second)) + '';
	if (minute > 0) {
		result = '' + (parseInt(minute)<10?'0'+parseInt(minute):parseInt(minute))+ ':' + result;
	}else{
		result = '00:' + result;
	}
	if (hour > 0) {
		result = '' +(parseInt(hour)<10?'0'+parseInt(hour):parseInt(hour)) + ':' + result;
	}else{
		result = '00:'+ result;
	}
	//  if (day > 0) {
	//    result = '' + parseInt(day) + '天' + result
	//  }
	//console.log('秒转化时分秒结果', result);
	return result;
}

function formatRelativeTime(stringTime) {
	let timestamp = parseTime(stringTime).getTime();
    const currentTime = new Date().getTime();
    const timeDifference = currentTime - timestamp;
    if (timeDifference < 60000) { // 少于1分钟
        return '刚刚';
    } else if (timeDifference < 3600000) { // 少于1小时
        const minutes = Math.floor(timeDifference / 60000);
        return `${minutes}分钟前`;
    } else if (timeDifference < 86400000) { // 少于1天
        const hours = Math.floor(timeDifference / 3600000);
        return `${hours}小时前`;
    } else if (timeDifference < 172800000) { // 少于2天，即昨天
        const yesterday = new Date(currentTime - 86400000);
        const yesterdayYear = yesterday.getFullYear();
        const yesterdayMonth = ('0' + (yesterday.getMonth() + 1)).slice(-2);
        const yesterdayDay = ('0' + yesterday.getDate()).slice(-2);
        const formattedYesterday = `${yesterdayYear}-${yesterdayMonth}-${yesterdayDay}`;
        const yesterdayTime = new Date(timestamp);
        const hours = ('0' + yesterdayTime.getHours()).slice(-2);
        const minutes = ('0' + yesterdayTime.getMinutes()).slice(-2);
        return `昨天 ${hours}:${minutes}`;
    } else if (timeDifference < 604800000) { // 少于1周
        const days = Math.floor(timeDifference / 86400000);
        return `${days}天前`;
    } else if (timeDifference < 2592000000) { // 少于1个月，考虑周
        const weeks = Math.floor(timeDifference / 604800000);
        return `${weeks}周前`;
    } else {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
    }
}


//获取随机数
function randomNum(minNum,maxNum){
	switch(arguments.length)
	{
	case 1:
	return parseInt(Math.random()*minNum+1,10);
	break;
	case 2:
	return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
	break;
	default:
	return 1;
	break;
	}
}
// 防止处理多次点击
function noMultipleClicks(methods, info) {
    // methods是需要点击后需要执行的函数， info是点击需要传的参数
    let that = this;
    if (that.noClick) {
        // 第一次点击
        that.noClick= false;
        if(info && info !== '') {
            // info是执行函数需要传的参数
            methods(info);
        } else {
            methods();
        }
        setTimeout(()=> {
            that.noClick= true;
        }, 1000)
    } else {
        //utilAlert("慢点戳!");
    }
}

//清除本地缓存文件（废弃，没有调用）
function clearLocalFile() {
	uni.getSavedFileList({
		success: function(res) {
			let fileList = res.fileList;
			if (fileList.length > 0) {
				for (var i = 0; i < fileList.length; i++) {
					let localFile = fileList[i];
					let localPath = localFile.filePath;
					let localFileSize = localFile.size;
					uni.removeSavedFile({
						filePath: localPath,
						complete: function(res) {
							//console.log("删除本地文件结果",res);
						}
					});
				};
			}
		}
	});
	const res = uni.getStorageInfoSync();
	let keys = res.keys;
	for (var i = 0; i < keys.length; i++) {
		let key = keys[i];
		if (key.indexOf('image') != -1 || key.indexOf('video') != -1) {
			uni.removeStorage({
				key: key,
				success: function(res) {
					//console.log("文件"+key+"已被清除");
				}
			});
		}
	}
}

module.exports = {
	utilAlert: function (msg, iconType) {
			return utilAlert(msg, iconType);
	},
	utilLoading:function (tip,mask){
	    return utilLoading(tip, mask);
	},
	palyMsgTips:function(index){
		return palyMsgTips(index);
	},
	palyMsgTipSelected: function(that,groupId) {
		return palyMsgTipSelected(that,groupId);
	},

	clearVuex:function(that){
		return clearVuex(that);
	},
	byteConvert:function(bytes){
		return byteConvert(bytes);
	},
	globalUpload: function(that,callback){
		  globalUpload(that,callback);
	},
	getVideoImage:function(that,tempFilePath,callback){
		let plat=  uni.getSystemInfoSync().platform;
		//console.log("=============当前平台==========",plat);
		// #ifdef APP-PLUS
		if(plat=="ios"){
			return iosCreateVideoThumbnail(that,tempFilePath,callback);
		}
		if(plat=="android"){
			return androidCreateVideoThumbnail(that,tempFilePath,callback);
		}
		// #endif
		// #ifndef APP-PLUS
			//console.log("================不支持的平台============")
			callback.complete("");
		// #endif
	},
	scanQRcode:function(that,callback){
		 scanQRcode(that,callback);
	},
	uniCopy:function({content,success,error}){
		return uniCopy({content,success,error});
	},
	parseTime:function(timeStr){
		return parseTime(timeStr);
	},
	formatSeconds:function(seconds){
		return formatSeconds(seconds);
	},
	// 通过时间戳获取正常的时间显示
	getTimeStr:function(timestamp,type){
		return getTimeStr(timestamp,type);
	},
	fromatMsgTime:fromatMsgTime,
	formatRelativeTime:formatRelativeTime,
	randomNum:function(min,max){
		return randomNum(min,max);
	},
	noMultipleClicks:noMultipleClicks,
	scan_business_code:scan_business_code,
	transform: transform,
	clearLocalFile: clearLocalFile,
	getCid: function(callback) {
		return getCid(callback)
	},
}
